package com.lagou.consumer;

import com.lagou.pojo.OrderDetail;
import com.lagou.service.OrderService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Date;

@Component
public class MyMessageListener {

    @Autowired
    OrderService orderService;

//    @RabbitListener(queues = "queue.boot")
//    public void getMyMessage(@Payload String message, @Header(name = "hello") String value, Channel channel) {
//        System.out.println(message);
//        System.out.println("hello = " + value);
//
//        // 确认消息
//        channel.basicAck();
//        // 拒收消息
//        channel.basicReject();
//    }

    private Integer index = 0;

    /**
     * 监听私信队列里的值
     * @param message
     * @param channel
     * @throws IOException
     */
    @RabbitListener(queues = "q.go.dlx")
    public void getMyMessage(Message message, Channel channel) throws IOException {

        String orderCode = new String(message.getBody());
        System.out.println("超时订单  =>>>>>>  " + orderCode);
        //需要确实收到消息，否则死信队列消息会一直存在
        final long deliveryTag = message.getMessageProperties().getDeliveryTag();
        if (index % 2 == 0) {
            // 确认消息
            channel.basicAck(deliveryTag, false);
        } else {
            // 拒收消息
            channel.basicReject(deliveryTag, false);
        }
        index++;

        OrderDetail orderDetail = orderService.findByOrderCode(orderCode);
        System.out.println("start...");
        if(orderDetail == null){
            System.err.println("orderCode  未查询到相应订单=>>>>>>  " + orderCode);
            return;
        }
        //订单已支付
        if(orderDetail.getIsPay() == 1){
            System.err.println("orderCode 订单已支付=>>>>>>  " + orderCode);
            return;
        }
        //订单未支付
        orderDetail.setIsPay(0);
        //订单已超时
        orderDetail.setStatus(1);
        orderDetail.setModified(new Date());
        orderService.saveOrUpdate(orderDetail);
    }

}
